﻿#region Copyright(C) 2018 FI Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME      : FI.Net Application Framework
// COMPONENT ID     : ApplicationContext
// COMPONENT DESC   : Session based contextual data sharing.
//
// CREATED DATE/BY  : 18 Aug 2018 / Tian Mi
//
// REVISION HISTORY :
// DATE/BY            SR#/CS/PM#/OTHERS      DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion

using FI.Core.Utilities;
using System;

namespace FI.Core.ApplicationContexts
{
    /// <summary>
    /// This class defines some extensions methods against <see cref="ApplicationContext"/>.
    /// </summary>
    public static class ApplicationContextExtensions
    {
        /// <summary>
        /// Clone the specified <see cref="ApplicationContext"/> and create a new <see cref="DependentApplicationContext"/>.
        /// </summary>
        /// <param name="context">The <see cref="DependentApplicationContext"/> to be cloned.</param>
        /// <returns>The <see cref="DependentApplicationContext"/></returns>.
        public static DependentApplicationContext DependentClone(this ApplicationContext context)
        {
            Guard.ArgumentNotNull(context, "context");

            ContextItemCollection currentContextItems = context.ContextLocator.GetCurrentContext();
            ContextItemCollection newContextItems = new ContextItemCollection();
            foreach (ContextItem item in currentContextItems)
            {
                object value = item.Value;
                ICloneable cloneable = value as ICloneable;
                if (null != cloneable)
                {
                    value = cloneable.Clone();
                }
                ContextItem newItem = new ContextItem(item.Key, value, item.IsLocal);
                if (item.ReadOnly)
                {
                    newItem.ReadOnly = true;
                }
                newContextItems.Add(newItem);
            }
            return new DependentApplicationContext(newContextItems);
        }
    }
}